package com.payment.ktb.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.android.volley.VolleyError;
import com.payment.ktb.Interface.AlertInterface;
import com.payment.ktb.Interface.HttpCallbackListener;
import com.payment.ktb.R;
import com.payment.ktb.constants.Constants;
import com.payment.ktb.constants.HttpActions;
import com.payment.ktb.constants.HttpUrls;
import com.payment.ktb.model.BindCardEntity;
import com.payment.ktb.utils.AlertDialogUtils;
import com.payment.ktb.utils.HttpUtils;
import com.payment.ktb.utils.SharedPreferencesUtils;
import com.payment.ktb.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by syd on 2016/6/2.
 */
public class RegisterActivity extends BaseActivity{

    private long totalTime = 62000;
    private long intervalTime = 1000;



    String phone ;
    String code ;
    String pass;
    String org;

    MyCountDownTimer countDownTimer;
    @BindView(R.id.et_registeractivity_phone)
    EditText et_registeractivity_phone;
    @BindView(R.id.et_registeractivity_code)
    EditText et_registeractivity_code;
    @BindView(R.id.et_registeractivity_pass)
    EditText et_registeractivity_pass;
    @BindView(R.id.et_registeractivity_orgId)
    EditText et_registeractivity_orgId;
    @BindView(R.id.btn_registeractivity_obtaincode)
    Button btn_registeractivity_obtaincode;
    @BindView(R.id.iv_register_aggreprotocol)
    ImageView iv_register_aggreprotocol;
    @BindView(R.id.iv_register_passwordstatus)
    ImageView iv_register_passwordstatus;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);
        initTitle("注册");
        et_registeractivity_pass.addTextChangedListener(textWatcher);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        phone = et_registeractivity_phone.getText().toString().trim();
        code = et_registeractivity_code.getText().toString().trim();
        pass = et_registeractivity_pass.getText().toString().trim();
        org = et_registeractivity_orgId.getText().toString().trim();
    }


    /**
     *
     * @param view
     */
    @OnClick({R.id.btn_registeractivity_obtaincode,R.id.btn_registeractivity_submit,R.id.tv_register_protocol,R.id.rl_register_saveuserprotocol,R.id.rl_register_deletephone,R.id.rl_registeractivity_passwordvalid,R.id.ll_register_phone})
    public void clickEvent(View view) {
        switch (view.getId()) {
            case R.id.btn_registeractivity_obtaincode:
                initData();
                if (TextUtils.isEmpty(phone) || phone.length() != 11) {
                    ToastUtils.showToast("请输入11位手机号码！");
                } else {
                    obtainMsgCode();
                }
                break;


            case R.id.btn_registeractivity_submit:
                initData();
                if (checkPass()) {
                    submit();
                }
                break;

            //清空手机号
            case R.id.rl_register_deletephone:
                et_registeractivity_phone.setText("");
                break;

            //清空密码
            case R.id.rl_registeractivity_passwordvalid:
                et_registeractivity_pass.setText("");
                break;

            //拨打客服
            case R.id.ll_register_phone:

                AlertDialogUtils.showAlertDialog(mContext, "400-101-8258", "取消", "呼叫", new AlertInterface() {
                    @Override
                    public void confirm(Dialog alertDialog) {
                        startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:4001018258")));
                    }
                });


                break;


            //注册协议
            case R.id.tv_register_protocol:
                startActivity(ProtocolActivity.class);
                break;

            //同意用户协议
            case R.id.rl_register_saveuserprotocol:
                if (SharedPreferencesUtils.getBoolean("userprotocol",true)) {
                    SharedPreferencesUtils.putBoolean("userprotocol",false);
                    iv_register_aggreprotocol.setImageResource(R.mipmap.login_unchecked);
                } else {
                    SharedPreferencesUtils.putBoolean("userprotocol",true);
                    iv_register_aggreprotocol.setImageResource(R.mipmap.login_check);
                }
                break;


        }
    }


    /**
     *检查参数输入是否完整
     */
    private boolean checkPass() {
        if (TextUtils.isEmpty(phone)) {
            ToastUtils.showToast("请输入手机号码");
            return false;
        } else if (phone.length() != 11) {
            ToastUtils.showToast("手机号码不正确");
            return false;
        }else if (TextUtils.isEmpty(code)) {
            ToastUtils.showToast("请输入验证码");
            return false;
        } else if (code.length() > 6) {
            ToastUtils.showToast("验证码位数不大于6位");
            return false;
        } else if (TextUtils.isEmpty(pass) || pass.length() < 6) {
            ToastUtils.showToast("请输入6-20位密码");
            return false;
        } else if (TextUtils.isEmpty(org)) {
            ToastUtils.showToast("请输入邀请码");
            return false;
        } else if (!SharedPreferencesUtils.getBoolean("userprotocol",true)) {
            ToastUtils.showToast("需同意服务协议！");
            return false;
        } else {
            return true;
        }
    }

    /**
     *
     */
    private void submit() {

        progressDialogUtils.showProgress();

        //构造传输参数

        String phone = et_registeractivity_phone.getText().toString().trim();
        String code = et_registeractivity_code.getText().toString().trim();
        String pass = et_registeractivity_pass.getText().toString().trim();


        //将参数放入map中
        HashMap<String, String> map = new HashMap<String,String>();

        map.put("phone",phone);
        map.put("code", code);
        map.put("pass", pass);
        map.put("org", org);
        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.UserRegisterState, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                progressDialogUtils.dismissProgress();
                ToastUtils.showToast("注册成功！");
                startActivityThenKill(LoginActivity.class);
            }

            @Override
            public void onError(VolleyError volleyError) {

                progressDialogUtils.dismissProgress();
                AlertDialogUtils.showAlertDialog(mContext, volleyError.getMessage());

            }
        });

    }

    /**
     * 获取注册的短信验证码
     */
    private void obtainMsgCode() {
        countDownTimer = new MyCountDownTimer(totalTime,intervalTime);
        countDownTimer.start();
        progressDialogUtils.showProgress();

        //构造传输参数
        String phone = et_registeractivity_phone.getText().toString().trim();

        //将参数放入map中
        HashMap<String, String> map = new HashMap<String,String>();
        map.put("phone",phone);

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.UserRegisterStateSms, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                progressDialogUtils.dismissProgress();
                ToastUtils.showToast("获取验证码成功！");
            }

            @Override
            public void onError(VolleyError volleyError) {
                progressDialogUtils.dismissProgress();
                AlertDialogUtils.showAlertDialog(mContext, volleyError.getMessage());
                countDownTimer.cancel();
                btn_registeractivity_obtaincode.setEnabled(true);
                btn_registeractivity_obtaincode.setText("重新获取");
            }
        });


    }


    /**
     * 获取短信验证码的时候，显示倒计时
     */
    class MyCountDownTimer extends CountDownTimer {

        /**
         *
         * @param millisInFuture
         *            倒计时总时间
         * @param countDownInterval
         *            每隔多久触发onTick方法
         */
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onFinish() {
            btn_registeractivity_obtaincode.setText("重新获取");
            btn_registeractivity_obtaincode.setEnabled(true);
        }

        @Override
        public void onTick(long arg0) { // arg0 表示距离本级倒计时结束还有多长时间

            btn_registeractivity_obtaincode.setText("重新获取" + "(" + ((arg0 / 1000) -1) + ")" );
            btn_registeractivity_obtaincode.setEnabled(false);

        }

    }



    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            String etValues = s.toString();
            if (!TextUtils.isEmpty(etValues) && etValues.length() >= 6 && etValues.length() <= 20) {
                iv_register_passwordstatus.setImageResource(R.mipmap.password_checkmark);
            }else {
                iv_register_passwordstatus.setImageResource(R.mipmap.password_checkmark_grey);
            }
        }

    };



}
